

const text = '🐶 🐱 🐭 🐹 🐰 🦊 🦝 🐻 🐼 🦘 🦡 🐨 🐯 🦁 🐮 🐷 🐽 🐸 🐵 🙈 🙉 🙊 🐒 🐔 🐧 🐦 🐤 🐣 🐥 🦆 🦢 🦅 🦉 🦚 🦜 🦇 🐺 🐗 🐴 🦄 🐝 🐛 🦋 🐌 🐚 🐞 🐜 🦗 🕷 🕸 🦂 🦟 🦠 🐢 🐍 🦎 🦖 🦕 🐙 🦑 🦐 🦀 🐡 🐠 🐟 🐬 🐳 🐋 🦈 🐊 🐅 🐆 🦓 🦍 🐘 🦏 🦛 🐪 🐫 🦙 🦒 🐃 🐂 🐄 🐎 🐖 🐏 🐑 🐐 🦌 🐕 🐩 🐈 🐓 🦃 🕊 🐇 🐁 🐀 🐿 🦔 🐾 🐉 🐲 🌵 🎄 🌲 🌳 🌴 🌱 🌿 ☘️ 🍀 🎍 🎋 🍃 🍂 🍁 🍄 🌾 💐 🌷 🌹 🥀 🌺 🌸 🌼 🌻 🌞 🌝 🌛 🌜 🌚 🌕 🌖 🌗 🌘 🌑 🌒 🌓 🌔 🌙 🌎 🌍 🌏 💫 ⭐️ 🌟 ✨ ⚡️ ☄️ 💥 🔥 🌪 🌈 ☀️ 🌤 ⛅️ 🌥 ☁️ 🌦 🌧 ⛈ 🌩 🌨 ❄️ ☃️ ⛄️ 🌬 💨 💧 💦 ☔️ ☂️ 🌊'
const emojis = text.split(' ')
const emojis2 = '👆 👇 👈 👉'.split(' ')
const key = 'game'
function loadRecords() { // 读取排行榜
  return JSON.parse(localStorage.getItem(key)) || {}
}
function saveRecords(records) { // 保存排行榜
  localStorage.setItem(key, JSON.stringify(records))
}
function makeRecords(records, gameLevel, time) { // 获取新的排行数据
  const times = records[gameLevel] || []
  const newTimes = [...times, time]
          .sort((a,b) => a-b).slice(0, 3)
  records[gameLevel] = newTimes
  return records
}
// console.log(makeRecords({}, 0, 1000))
let records = loadRecords()

// 获取随机数
function rand(m, n, int = false) {
  const r = Math.random() * (n - m) + m
  return int ? Math.floor(r) : r
}
// 查询方法
function $(selector) {
  return document.querySelector(selector)
}
// 隐藏所有界面
function hideAll() {
  container.style.display = 'none'
  start.style.display = 'none'
  won.style.display = 'none'
  gameOver.style.display = 'none'
}
// 创建item
function makeItem(size = 64, emojis) {
  const { clientWidth, clientHeight } = document.documentElement
  const [MIN_SPEED, MAX_SPEED] = [0.5, 2]
  const item = {
    t: emojis[rand(0, emojis.length, true)],
    dx: (Math.random() > 0.5 ? 1 : -1) * rand(MIN_SPEED, MAX_SPEED), // x方向速度
    dy: (Math.random() > 0.5 ? 1 : -1) * rand(MIN_SPEED, MAX_SPEED), // y方向速度
    x: rand(0, clientWidth - size),
    y: rand(0, clientHeight - size),
    el: null,
    init: function () { // 初始化
      this.el = document.createElement('div')
      this.el.className = 'item'
      this.el.innerText = this.t
      this.el.style.width = size + 'px'
      this.el.style.height = size + 'px'
      this.el.style.fontSize = size + 'px'
      this.el.style.left = this.x + 'px'
      this.el.style.top = this.y + 'px'
      container.append(this.el)

      // this.el.onclick = () => {
      //   const f = this.dx === 0 && this.dy === 0
      //   if (f) {
      //     console.log('你赢了')
      //   } else {
      //     console.log('点错了，还有n次机会')
      //   }
      // }
    },
    move: function () { // 移动
      const { clientWidth, clientHeight } = document.documentElement
      let x = this.x + this.dx
      let y = this.y + this.dy
      // 碰撞左右边界
      if (x < 0 || x > clientWidth - size) {
        this.dx = -this.dx
      }
      // 碰撞上下边界
      if (y < 0 || y > clientHeight - size) {
        this.dy = -this.dy
      }
      // 修正x y 位置，不超出屏幕范围
      x = x < 0 ? 0 : x
      x = x > clientWidth - size ? (clientWidth - size) : x
      y = y < 0 ? 0 : y
      y = y > clientHeight - size ? (clientHeight - size) : y

      this.x = x
      this.y = y
      this.el.style.left = this.x + 'px'
      this.el.style.top = this.y + 'px'
    },
    remove() {
      this.el.remove()
    }
  }
  item.init()
  return item
}

let begin = 0 // 时间戳 1970-1-1 00:00:00 开始到现在的毫秒数
let items = null
let n = 0

// 新游戏
// const obj = {a: {}}
// console.log(obj && obj.a && obj.a.b && obj.a.b.c)
// console.log(obj.a?.b?.c)
let currentGameLevel = 0 // 当前难度
function newGame(level=0) {
  items?.forEach(item => item.remove())
  currentGameLevel = level
  container.style.display = 'block'
  begin = Date.now()
  n = 3
  if(level===0) {
    items = [...Array(30)].map(() => makeItem(64, emojis))
  } else if(level===1) {
    items = [...Array(180)].map(() => makeItem(64, emojis2))
  }
  // 随机选一个item作为不动的
  const item = items[rand(0, items.length, true)]
  item.dx = item.dy = 0
  run()
}

function gotoWon(item, ms) {
  records = makeRecords(records, currentGameLevel, ms)
  saveRecords(records)

  hideAll()
  won.style.display = 'block'
  $('#find').innerText = item.t
  $('#time').innerText = (ms / 1000).toFixed(2)
  $('#levelText').innerText = currentGameLevel === 0 ?
    '简单难度' : '困难难度'
  $('#records').innerHTML = records[currentGameLevel].map(
    time => `<li>${(time/1000).toFixed(3)}秒
      ${time === ms ? '⬅️':''}
    </li>`
  ).join('')
}
// 游戏失败
function gotoGameOver() {
  hideAll()
  gameOver.style.display = 'block'
}
// 开始界面
function gotoStart() {
  hideAll()
  start.style.display = 'block'
}

document.querySelectorAll('.back').forEach(
  btn => btn.onclick = gotoStart
)
// 计时器运行
let timer = 0
function run() {
  let t = 0
  timer = setInterval(() => {
    items.forEach(item => item.move())
    updateInfo(n, Date.now() - begin)
    if (t%180 === 0) {
      container.style.backgroundColor =
        `rgb(${rand(0, 255)}, ${rand(0, 255)}, ${rand(0, 255)})`
    }
    t++
  }, 1000 / 60) // setInterval(fn, ms)
  // setInterval(fn, 100)
}
// 计时器停止
function stop() {
  clearInterval(timer)
  timer = 0
}


const container = $('#container') // 游戏容器
const start = $('#start') // 开始界面
const won = $('#won') // 获胜界面
const gameOver = $('#gameOver') // 失败界面
const easyBtn = $('#easyBtn') // 简单按钮
easyBtn.onclick = () => {
  hideAll()
  newGame(0)
}
const hardBtn = $('#hardBtn') // 困难按钮
hardBtn.onclick = () => {
  hideAll()
  newGame(1)
}
const info = $('#info')
function updateInfo(n, ms) {
  info.innerText = `你还有${n}次机会，已经用时${(ms / 1000).toFixed(1)}秒。`
}
// 点击容器，进行游戏
container.onclick = (e) => {
  const { x, y } = e
  const f = items.find(item => {
    const rect = item.el.getBoundingClientRect()
    return (x >= rect.x && x <= rect.x + rect.width) &&
      (y >= rect.y && y <= rect.y + rect.height) &&
      item.dx === 0 && item.dy === 0
  })
  if (f) {
    stop()
    gotoWon(f, Date.now() - begin)
  } else {
    n = n - 1
    if (n === 0) {
      stop()
      gotoGameOver()
    }
  }
}



